﻿using Furion.DatabaseAccessor;
using Furion.JsonSerialization;
using Furion.RemoteRequest.Extensions;
using System;
using System.Linq;
using System.Threading.Tasks;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using iemtm.WeChat.Core.Extension;
using Furion.DataEncryption;

namespace iemtm.WeChat.Core.Extension.Helper
{
    /// <summary>
    /// 微信相关·方法
    /// </summary>
    public class WeChatHelper
    {
        public static  string Token ="ietem";//与微信公众账号后台的Token设置保持一致，区分大小写。

        public static WeixinConfig WeiXinConfig { get { return MemoryEntity.gBuffWeiXinConfig.All.First().Value; } }
     

        /// <summary>
        /// 获取微信Token
        /// </summary>
        public async static Task<AccessToken> GetAccessTokenAsync()
        {
           
            string WeiXinUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", WeiXinConfig.appID, WeiXinConfig.appsecret);
            // 发送 Get 请求
            var response = await WeiXinUrl.GetAsync();
            string resultV = response.Content.ReadAsStringAsync().Result;
            var result = JSON.GetJsonSerializer().Deserialize<AccessToken>(resultV.ToString());
          
            return result;
        }

        /// <summary>
        /// 获取ticket
        /// </summary>
        public async static Task<JsapiTicketModel> GetJsApiTicketAsync()
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", WeiXinConfig.access_token);
            // 发送 Get 请求
            var response = await url.GetAsync();
            string resultV = response.Content.ReadAsStringAsync().Result;
            var result = JSON.GetJsonSerializer().Deserialize<JsapiTicketModel>(resultV);
            return result;


        }
        

        /// <summary>
        /// 创建目录
        /// </summary>
        /// <returns></returns>
        public async static Task<string> CreateMenu(MenuFull_ButtonGroup Menudata)
        {
            
            string url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + WeiXinConfig.access_token;
           var response=await url.SetBody(Menudata).SetContentType("application/json").PostAsync();
            string resultV = response.Content.ReadAsStringAsync().Result;
            return resultV;
        }


        /// <summary>
        /// 获取微信网页授权路径
        /// </summary>
        /// <param name="redirect_uri">授权后重定向的回调链接地址， 请使用 urlEncode 对链接进行处理</param>
        /// <returns></returns>
        public  static string GetOAuthUrl(string redirect_uri)
        {      
            string Url=string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}{2}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect",
               WeiXinConfig.appID, WeiXinConfig.domain, redirect_uri);
    
            return Url;

        }

        /// <summary>
        /// 通过网页授获取用户信息
        /// </summary>
        /// <param name="code">网页授获授权返回的code</param>
        /// <returns></returns>
        public async static Task<OAuthUserInfo> GetWxUserInfo(string code)
        {

            
            string UrlCode = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code",
                WeiXinConfig.appID, WeiXinConfig.appsecret,code);
            var responseCode=await UrlCode.GetAsync();
            var resultCode=responseCode.Content.ReadAsStringAsync().Result;
            var token= JSON.GetJsonSerializer().Deserialize<OAuthAccessTokenResult>(resultCode);

            string UrlUserInfo = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", token.access_token, token.openid);
            var responseUserInfo = await UrlUserInfo.GetAsync();
            var resultUserInfo = responseUserInfo.Content.ReadAsStringAsync().Result;
            var UserInfo= JSON.GetJsonSerializer().Deserialize<OAuthUserInfo>(resultUserInfo);

            return UserInfo;
        }


        /// <summary>
        /// 生产JsapiTicket签名
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static JsapiTicketSignatureModel CreateTicketSignature(string url)
        {
            // 测试 MD5 加密，比较

            JsapiTicketSignatureModel result = new JsapiTicketSignatureModel() { 
                nonceStr = Token, 
                appId = WeiXinConfig.appID, 
                jsapi_ticket = WeiXinConfig.jsapi_ticket, 
                timestamp = DateTime.Now.ConvertDateTimeInt(),
                url = $"{url.Replace("http://", "").Insert(0, "http://")}" };
            string tmpStr = $"jsapi_ticket={WeiXinConfig.jsapi_ticket}&noncestr={result.nonceStr}&timestamp={result.timestamp}&url={result.url}";
            result.signature = tmpStr.ToSHA1Encrypt().ToLower();
            return result;
        }
    }



    #region WeChar 数据实体类
    public class AccessToken
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }
    }
    public class JsapiTicketSignatureModel
    {
        //appId: '', // 必填，公众号的唯一标识
        //timestamp: , // 必填，生成签名的时间戳
        //nonceStr: '', // 必填，生成签名的随机串
        //signature: '',// 必填，签名
        //jsApiList: [] // 必填，需要使用的JS接口列表
        public string appId { get; set; }
        public string jsapi_ticket { get; set; }
        public int timestamp { get; set; }
        public string nonceStr { get; set; }
        public string signature { get; set; }
        public string url { get; set; }
        public string jsApiList { get; set; }
    }


    public class JsapiTicketModel
    {
        public int errcode { get; set; }
        public string errmsg { get; set; }
        public string ticket { get; set; }
        public int expires_in { get; set; }
    }
    #endregion

}
